package com.lxs.legou.order.service.impl;
import com.lxs.legou.item.po.Sku;
import com.lxs.legou.item.po.Spu;
import com.lxs.legou.order.client.SkuClient;
import com.lxs.legou.order.client.SpuClient;
import com.lxs.legou.order.po.OrderItem;
import com.lxs.legou.order.service.CartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;


/**
 * @Auther: Mcb
 * @Date: 2022/1/9 21:57
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuClient skuClient;
    @Autowired
    private SpuClient spuClient;
    @Autowired
    private RedisTemplate redisTemplate;

    Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);


    /**
     * @param skuId    商品的不可再分的最小单元
     * @param num      购买数量
     * @param userName 购买的商品的用户名
     *
     * @Description: 将购物数据存入redis，使用hash结构，“Cart+username”，[（skuId，orderItem）...]
     */
    @Override
    public boolean add(Long skuId, Integer num, String userName) {
        Sku skuData = skuClient.edit(skuId);

        if (skuData == null){
            logger.error("商品编号："+skuId+"错误");
            return false;
        }

        Spu spu = spuClient.edit(skuData.getSpuId());
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCid1());
        orderItem.setCategoryId2(spu.getCid2());
        orderItem.setCategoryId3(spu.getCid3());
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(skuId);
        orderItem.setName(skuData.getTitle());//商品标题名称 sku的名称
        orderItem.setPrice(skuData.getPrice());//sku单价
        orderItem.setNum((long)num);
        orderItem.setPayMoney(orderItem.getNum()*orderItem.getPrice());//总价= 单价*数量
        orderItem.setMoney(skuData.getPrice()*num);
        orderItem.setImage(skuData.getImages());

        redisTemplate.boundHashOps("Cart_"+userName).put(skuId,orderItem);
        return true;
    }

    /**
     * 删除购物车商品
     *
     * @param skuId
     * @param userName
     * @return
     */
    @Override
    public boolean delete(Long skuId, String userName) {
        Long deleteState = redisTemplate.boundHashOps("Cart_" + userName).delete(skuId);
        return deleteState<=0?false:true;
    }

    /**
     * 从redis中查询当前用户对应的购物车数据
     *
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        return redisTemplate.boundHashOps("Cart_"+username).values();
    }
}
